//package com.binguo.wxapi.controller;
//
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//
//
//import com.binguo.common.exception.ServiceException;
//import com.binguo.common.util.Jpush.push.JPushUtil;
//import com.binguo.helper.FaceHelperV3;
//import com.binguo.model.api.vo.BinguoOrderVO;
//import com.binguo.model.mapper.*;
//import com.binguo.model.model.*;
//
//import com.binguo.model.wxapi.vo.AiyouweiGetCellVO;
//import com.binguo.model.wxapi.vo.OpenCellByCardNoVO;
//import com.binguo.model.wxapi.vo.SideBoardVO;
//
//import com.binguo.service.OrderService;
//import com.binguo.service.QrCodePayQCGService;
//import com.binguo.common.sms.JavaSmsApi;
//
//
//import com.binguo.wxapi.form.PhoneMealsForm;
//import com.binguo.wxapi.form.aiyouwei.SaveOrderForm;
//import com.binguo.wxapi.result.Result;
//import com.binguo.wxapi.result.ResultGenerator;
//import com.binguo.wxapi.service.AiyouweiService;
//import com.binguo.wxapi.service.ApiService;
//import com.binguo.wxapi.util.AiyouweiUtils;
//import com.binguo.wxapi.util.CommandCode;
//
//import com.binguo.model.wxapi.vo.UmengPushVo;
//import com.github.pagehelper.util.StringUtil;
//import org.apache.http.ParseException;
//
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.transaction.PlatformTransactionManager;
//import org.springframework.transaction.TransactionDefinition;
//import org.springframework.transaction.TransactionStatus;
//import org.springframework.transaction.support.DefaultTransactionDefinition;
//
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.*;
//import sun.misc.BASE64Decoder;
//
//
//import tk.mybatis.mapper.entity.Condition;
//
//
//import javax.annotation.Resource;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.OutputStream;
//import java.util.*;
//import java.sql.Timestamp;
//
//import static com.sun.tools.doclint.Entity.and;
//
//
///**
// * 所有和只能餐柜的都在这里面
// */
//@RestController
//public class AiyouweiController {
//
//    @Autowired
//    private AiyouweiUtils aiyouweiUtils;
//
//    @Resource
//    private ShopConfigExtendMapper shopConfigExtendMapper;
//
//    @Autowired
//    OrderService orderService;
//
//    @Autowired
//    AiyouweiService aiyouweiService;
//
//    @Resource
//    private SideBoardMapper sideBoardMapper;
//
//    @Resource
//    private BinguoOrderMapper binguoOrderMapper;
//
//    @Resource
//    private SideBoardCellDetailMapper sideBoardCellDetailMapper;
//
//    @Resource
//    private SideBoardCellsMapper sideBoardCellsMapper;
//
//    @Autowired
//    private PlatformTransactionManager txManager;
//
//    @Resource
//    private PayCardMapper payCardMapper;
//    @Autowired
//    private ApiService apiService;
//
//    @Resource
//    private YpCardMapper ypCardMapper;
//    @Resource
//    private QrCodePayQCGService qrCodePayQCGService;
//    @Resource
//    private ShopMapper shopMapper;
//
////    @Resource
////    private UmengPushService umengPushService;
//    @Resource
//    private InitInfoMapper initInfoMapper;
//
//
//    public String wxapiFilepath = "/usr/local/nginx/html";
//
//
//    private static String ipAddress = System.getenv("ipAddress");
//
//
//    private static final Logger logger = LoggerFactory.getLogger(AiyouweiController.class);
//
//
//    /**
//     * 发送命令至餐柜
//     * @return
//     * @throws ParseException
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/openCell")
//    public JSONObject openCell(SideBoard sideBoard) throws ParseException, IOException {
//        //cellNo 从数据库里获取订单所在餐格，这里先用固定值
//        String[] cellNo = new String[]{"5"};
//        sideBoard.setAppid(66468);
//        sideBoard.setDeviceId("b5yp1yslhiVvoWTLq1Lc");
//        return JSONObject.parseObject(aiyouweiUtils.runCommand(cellNo, CommandCode.OPEN.getCode(),sideBoard));
//    }
//
//    /**
//     * 获取所有格子信息
//     * @return
//     * @throws ParseException
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getAllCell")
//    public JSONObject getAllCell(@RequestBody SideBoard sideBoard)throws ParseException, IOException {
//
//        return JSONObject.parseObject(aiyouweiUtils.querryAll(sideBoard));
//    }
//
//    /**
//     * 获取单个格子信息
//     * @return
//     * @throws ParseException
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getCell")
//    public JSONObject getCell() throws ParseException, IOException {
//        Integer cellNo = 5;
//
//        return JSONObject.parseObject(aiyouweiUtils.querry(cellNo));
//    }
//
//    /**
//     * 商户绑定餐柜时默认查询餐柜的格子状态并添加数据库
//     * @param sideBoard
//     * @return
//     * @throws ParseException
//     */
//    @PostMapping(value = "/api/wxapp/aiyouwei/init" )
//    public Result init(@RequestBody SideBoard sideBoard){
//        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//        TransactionStatus statu = txManager.getTransaction(def);
//        //初始化步骤
//        //1.side_board表插入信息
//        try {
//            aiyouweiService.initSideBoard(sideBoard);
//            //2.查询所有柜格状态并向side_board表插入信息
//            String side =  aiyouweiUtils.querryAll(sideBoard);
//            Map<String, Object> map = JSONObject.toJavaObject(JSONObject.parseObject(side), Map.class);
//            map = JSONObject.toJavaObject(JSONObject.parseObject(String.valueOf(map.get("Data"))), Map.class);
//            List<Map<String,Object>> obj = (List<Map<String,Object>>)map.get("Cells");
//            List<SideBoardCells> list = new ArrayList<>();
//            for(int i = 0; i < obj.size(); i++){
//                boolean status = false;
//                if(!String.valueOf(obj.get(i).get("CellStatus")).equals("1")){
//                    status = true;
//                }
//                list.add(SideBoardCells.builder().id(0).
//                        sideBoardId(sideBoard.getId()).
//                        status(status).cell(Integer.valueOf(String.valueOf(obj.get(i).get("CellNo")))).
//                        isWarm(false).build());
//            }
//            aiyouweiService.initSideBoardCells(list);
//        }catch (Exception e){
//            txManager.rollback(statu);
//            return ResultGenerator.genFailResult("绑定失败！");
//        }
//        txManager.commit(statu);
//        return ResultGenerator.genSuccessResult("绑定完成");
//    }
//
//    /**
//     * 下单确认页查询是否取餐和加热
//     * @param sideBoardVO
//     * @return
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getMealsPriceAndWarmPrice")
//    public Result getIsWramAndIsMeals(SideBoardVO sideBoardVO){
//        sideBoardVO = shopConfigExtendMapper.selectByShopIdAndBranchId(sideBoardVO.getShopId(), sideBoardVO.getBranchId());
//        if(sideBoardVO != null){
//
//            return ResultGenerator.genSuccessResult(sideBoardVO);
//
//        }else{
//            return ResultGenerator.genFailResult("未查询到商户！");
//        }
//    }
//
//    /**
//     * 更新或添加存餐和加热价格
//     * @param sideBoardVO
//     * @return
//     */
//    @PostMapping(value = "/api/wxapp/aiyouwei/updateShopConfigExtend")
//    public Result updataShopConfigExtend(@RequestBody SideBoardVO sideBoardVO){
//            int i = 0;
//            if(sideBoardVO.getId()==0){
//                ShopConfigExtend shopConfigExtend = new ShopConfigExtend();
//                shopConfigExtend.setBranchId(sideBoardVO.getBranchId());
//                shopConfigExtend.setSideBoardPrice(sideBoardVO.getPrice());
//                shopConfigExtend.setId(0);
//                shopConfigExtend.setShopId(sideBoardVO.getShopId());
//                shopConfigExtend.setWarmPrice(sideBoardVO.getWarm());
//                i = shopConfigExtendMapper.insert(shopConfigExtend);
//                if(i > 0){
//                    return ResultGenerator.genSuccessResult("新增成功！");
//                }else{
//                    return ResultGenerator.genFailResult("新增失败！");
//                }
//            }else{
//                i = shopConfigExtendMapper.updateShopConfigExtendById(sideBoardVO.getId(),
//                        sideBoardVO.getWarm(),
//                        sideBoardVO.getPrice());
//                if(i > 0){
//                    return ResultGenerator.genSuccessResult("修改成功！");
//                }else{
//                    return ResultGenerator.genFailResult("修改失败！");
//                }
//            }
//    }
//
//    /**
//     * 订单详细页面查询存餐和加热价格
//     * @param orderId
//     * @return
//     */
//    @GetMapping(value = "/api/wxapp/detail/surcharge/{orderId}")
//    public Result getSurcharge(@PathVariable String orderId){
//        BinguoOrderVO binguoOrderVO = orderService.getSurcharge(orderId);
//        if(0==binguoOrderVO.getIsMeals() || null == binguoOrderVO.getIsMeals()){
//            return ResultGenerator.genFailResult("该订单未选择存餐！");
//        }else {
//            SideBoardVO sideBoardVO = shopConfigExtendMapper.selectByShopIdAndBranchId(binguoOrderVO.getShopId(),binguoOrderVO.getBranchId());
//            if(0 == binguoOrderVO.getIsWarm() || null == binguoOrderVO.getIsMeals() ){
//                sideBoardVO.setWarm(null);
//            }
//            Integer branchShopId = sideBoardCellsMapper.selectShopBranchId(orderId);
//            sideBoardVO.setSideBranchId(branchShopId);
//            return ResultGenerator.genSuccessResult(sideBoardVO);
//        }
//    }
//
//    /**
//     * 获取订单详细页面二维码
//     * @return Base64图片编码
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwie/saveOrder")
//    public String savaOrder(SaveOrderForm saveOrderForm){
//        return aiyouweiService.getQrCode(saveOrderForm);
//    }
//
//
//
//    /**
//     * 按钮、取餐码、存餐和取餐
//     * @param saveOrderForm
//     * @return
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/openByWxButton")
//    public Result openByWxButton(SaveOrderForm saveOrderForm)throws Exception{
//        logger.info("进入按钮、取餐码开柜接口，入参:"+saveOrderForm.toString());
//
//        if(null != saveOrderForm.getMealCode() ){
//            List<SideBoardCellDetail> sbDetails = aiyouweiService.selectSbDetails(saveOrderForm);
//
//            if(sbDetails.size()<=0 || null == sbDetails ){
//                //取餐码不存在
//                return ResultGenerator.genFailResult("号码无效!");
//            }
//            saveOrderForm.setOrderId(sbDetails.get(0).getOrderId());
//        }
//        //如果客户id不为空则代表该请求来自客户订单页面
//        if(null != saveOrderForm.getCustomerId()){
//            logger.info("------------用户开柜部分,入参:"+saveOrderForm.getIsCustomer());
//            logger.info("------------是否为true:"+(!"true".equals(saveOrderForm.getIsCustomer())));
//            /*if(!"true".equals(saveOrderForm.getIsCustomer())){
//                return ResultGenerator.genFailResult("用户无存餐权限！");
//            }*/
//            //查询商户id 和 分店id
//            logger.info("------------查询订单");
//            BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
//            logger.info("------------查询订单完毕");
//            logger.info("------------查询订单所在柜子");
//            List<SideBoardCells> slist =  aiyouweiService.selectSideBoardCells(saveOrderForm.getOrderId());
//            logger.info("------------查询订单所在柜子完毕");
//
//            logger.info("根据订单id从数据库中查找cashierId,orderId:"+saveOrderForm.getOrderId());
//            //查找出柜子的id
//            List<Integer> sideBoardId = sideBoardCellsMapper.selectSideboardIdByOrderId(saveOrderForm.getOrderId());
//            //查找出对应的柜子
//            SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(sideBoardId.get(0));
//            if(null == saveOrderForm.getCashierDeskId()){
//                saveOrderForm.setCashierDeskId(sideBoard.getCashierDeskId());
//            }
//            //SideBoardVO sideBoardVO =
//                    //sideBoardMapper.selectByShopIdAndBranchId(binguoOrder.getBranchid(),binguoOrder.getShopid(),saveOrderForm.getCashierDeskId());
////            SideBoard sideBoard = new SideBoard();
////            sideBoard.setDeviceId(sideBoardVO.getDeviceId());
////            sideBoard.setAppid(sideBoardVO.getAppid());
//            //根据订单号查询订单状态
//            SideBoardCellDetailExample s = new SideBoardCellDetailExample();
//            SideBoardCellDetailExample.Criteria example = s.createCriteria();
//            example.andOrderIdEqualTo(saveOrderForm.getOrderId());
//            example.andOrderStatusEqualTo(1);
//            if(null != saveOrderForm.getMealCode()){
//                example.andMealCodeEqualTo(saveOrderForm.getMealCode());
//            }
//            List<SideBoardCellDetail> list = aiyouweiService.selectSideBoardCellDetail(s);
//            if(list.size() > 0){
//                //如果查询出来了就开柜
//                String [] cellNo = new String[list.size()];
//                for(int i = 0; i < list.size(); i++){
//                    cellNo[i] = list.get(i).getCell();
//                }
//                logger.info("调用开柜接口");
////        在线版        String res = aiyouweiUtils.runCommand(cellNo, CommandCode.OPEN.getCode(),sideBoard);
////                UmengPushVo pushVo = new UmengPushVo();
////                String res = umengPushService.sendAndroidBroadcast(cellNo,CommandCode.);
////                logger.info("开柜接口返回参数:"+res);
////                Map<String,Object> obj = getRes(res);
////                if(((Boolean)obj.get("Success")).booleanValue() == false){
////                    return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////                }
////                logger.info("判断是否加热");
////                if(null != binguoOrder.getIsWarm()){
////                    if(1 == binguoOrder.getIsWarm()){
////                        String warmRes = aiyouweiUtils.runCommand(cellNo, "1026",sideBoard);
////                        obj = getRes(warmRes);
////                        if(((Boolean)obj.get("Success")).booleanValue() == false){
////                            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////                        }
////                    }
////                }
//                UmengPushVo pushVo = new UmengPushVo();
//                pushVo.setCellNo(cellNo);
//                //取餐时关灯
//                pushVo.setLight(false);
//                pushVo.setOpen(true);
//                //设置提示信息,内容是文章标题
//                //用户开柜取餐如果该订单是保温订单则执行关闭保温操作
//                if(null != binguoOrder.getIsWarm()){
//                    if(binguoOrder.getIsWarm() == 1){
//                        pushVo.setWarm(false);
//                    }else{
//                        pushVo.setWarm(true);
//
//                    }
//                }
//                String str = JSON.toJSONString(pushVo);
//                logger.info("调用开柜接口:"+pushVo);
//                Map<String, String> parm = new HashMap<String, String>();
//                parm.put("msg",str);
//                parm.put("id",sideBoard.getJpushRegisterId());
//                Boolean flag = JPushUtil.jpushAndroid(parm);
//                //Boolean flag = umengPushService.sendAndroidBroadcast(pushVo);
//                if(!flag){
//                    return ResultGenerator.genFailResult("开柜失败！");
//                }
//                logger.info("更新sideBoardCellDetail表");
//                for(int i = 0; i < list.size(); i++){
//                    list.get(i).setOrderStatus(2);
//                    list.get(i).setEndTime(new Timestamp(new Date().getTime()));
//                    try{
//                        Integer num = aiyouweiService.updateSideBoardCellDetail(list.get(i));
//                        logger.info("更新sideBoardCellDetail表结果:"+num.toString());
//                    }catch (Exception e){
//                        logger.info(e.getMessage());
//                    }
//
//
//                }
//                List<SideBoardCells> sideBoardCells = new ArrayList<>();
//                for(SideBoardCells sideBoardCell : slist){
//                    sideBoardCell.setStatus(false);
//                    sideBoardCell.setOrderId(null);
//                    sideBoardCell.setMealCode(null);
//                    sideBoardCell.setIsWarm(false);
//                    sideBoardCells.add(sideBoardCell);
//                }
//                logger.info("更新sideBoardCells表");
//                for(SideBoardCells cells : sideBoardCells){
//                    sideBoardCellsMapper.updateByPrimaryKeySelective(cells);
//                }
//                //sideBoardCellsMapper.updateByPrimaryKeyList(sideBoardCells);
//
//                logger.info("取餐成功");
//                return ResultGenerator.genSuccessResult("取餐成功");
//            }else{
//                return ResultGenerator.genFailResult("当前客户无存餐订单。");
//            }
//        }else{
//            logger.info("------------商户开柜部分");
//            //如果为空则代表该请求来自商户订单页面
//            //1.首先查询该分店对应的柜子
//            //查询商户id 和 分店id
//            BinguoOrderVO binguoOrder = binguoOrderMapper.findIsMealByOrderNo(saveOrderForm.getOrderId());
//            AiyouweiGetCellVO aiyouweiGetCellVO =
//                    aiyouweiService.selectAllNotUseCell(saveOrderForm.getBranchId(),saveOrderForm.getShopId());
//
//            if(null != aiyouweiGetCellVO){
//                logger.info("------------取餐柜空余柜格:"+aiyouweiGetCellVO.getCell());
//                SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(aiyouweiGetCellVO.getSideBoardId());
//                //查询出来最新一条未使用的餐柜后调用开柜接口
////                SideBoard sideBoard = new SideBoard();
////                sideBoard.setAppid(Integer.valueOf(aiyouweiGetCellVO.getAppid()));
////                sideBoard.setDeviceId(aiyouweiGetCellVO.getDeviceId());
//                String[] cellNo = new String[]{aiyouweiGetCellVO.getCell().toString()};
//
//                //开柜成功更新记录
//                //cells表更新记录后做判断
//                String code = aiyouweiService.isOneOrderToSomeCell(saveOrderForm.getOrderId());
//                if("".equals(code)){
//                    code = aiyouweiService.getMealCode(saveOrderForm.getOrderId());
//                }
//                SideBoardCells boardCells =  SideBoardCells.builder().id(aiyouweiGetCellVO.getId()).
//                        status(true).cell(aiyouweiGetCellVO.getCell()).
//                        orderId(saveOrderForm.getOrderId()).mealCode(code).
//                        sideBoardId(aiyouweiGetCellVO.getSideBoardId()).isWarm(false).build();
//                //开柜还没加判断
////                logger.info("--------------执行开柜命令吗，开柜参数:"+cellNo,CommandCode.OPEN);
////                String res = aiyouweiUtils.runCommand(cellNo, CommandCode.OPEN.getCode(),sideBoard);
////                Map<String,Object> obj = getRes(res);
////                if(((Boolean)obj.get("Success")).booleanValue() == false){
////                    return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////                }
////                if(1 == binguoOrder.getIsWarm()){
////                    String warmRes = aiyouweiUtils.runCommand(cellNo, "1025",sideBoard);
////                    obj = getRes(warmRes);
////                    if(((Boolean)obj.get("Success")).booleanValue() == false){
////                        return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////                    }
////                    boardCells.setIsWarm(true);
////                }
////                UmengPushVo pushVo = new UmengPushVo();
//////                pushVo.setCellNo(cellNo);
//////                //存餐时开灯
//////                pushVo.setLight(true);
//////                pushVo.setOpen(true);
//////                //商户开柜存餐如果该订单是保温订单则执行打开保温操作
//////                if(binguoOrder.getIsWarm() == 1){
//////                    pushVo.setWarm(true);
//////                }else{
//////                    pushVo.setWarm(true);
//////                }
//////                logger.info("调用开柜接口:"+pushVo);
//////                Boolean flag = umengPushService.sendAndroidBroadcast(pushVo);
//////                if(flag == false){
//////                    return ResultGenerator.genFailResult("开柜失败！");
//////                }
//                UmengPushVo pushVo = new UmengPushVo();
//                pushVo.setCellNo(cellNo);
//                //存餐开灯
//                pushVo.setLight(true);
//                pushVo.setOpen(true);
//                //设置提示信息,内容是文章标题
//                //用户开柜取餐如果该订单是保温订单则执行关闭保温操作
//                if(null != binguoOrder.getIsWarm()){
//                    if(binguoOrder.getIsWarm() == 1){
//                        pushVo.setWarm(true);
//                    }else{
//                        pushVo.setWarm(false);
//
//                    }
//                }
//                String str = JSON.toJSONString(pushVo);
//                logger.info("调用开柜接口:"+pushVo);
//                Map<String, String> parm = new HashMap<String, String>();
//                parm.put("msg",str);
//                parm.put("id",sideBoard.getJpushRegisterId());
//                Boolean flag = JPushUtil.jpushAndroid(parm);
//                //Boolean flag = umengPushService.sendAndroidBroadcast(pushVo);
//                if(!flag){
//                    return ResultGenerator.genFailResult("开柜失败！");
//                }
//                aiyouweiService.updateSideBoardCells(boardCells);
//                List<SideBoardCellDetail> sideBoardCellDetails = aiyouweiService.getSideBoardCellsExample(saveOrderForm.getOrderId());
//                List<SideBoardCells> sideBoardCells = aiyouweiService.getSideBoardCells(saveOrderForm.getOrderId());
//                if(sideBoardCells.size() <= sideBoardCellDetails.size()){
//                    sideBoardCellDetails.get(0).setStartTime(new Timestamp(new Date().getTime()));
//                    sideBoardCellDetails.get(0).setCell(boardCells.getCell().toString());
//                    sideBoardCellDetails.get(0).setOrderStatus(1);
//                    logger.info("存餐更新:sideBoardCellDetail:"+sideBoardCellDetails);
//                    aiyouweiService.updateSideBoardCellDetail(sideBoardCellDetails.get(0));
//                }else{
//                    SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
//                    sideBoardCellDetail.setMealCode(code);
//                    sideBoardCellDetail.setId(0);
//                    sideBoardCellDetail.setShopId(saveOrderForm.getShopId());
//                    sideBoardCellDetail.setBranchId(saveOrderForm.getBranchId());
//                    sideBoardCellDetail.setOrderId(saveOrderForm.getOrderId());
//                    sideBoardCellDetail.setStartTime(new Timestamp(new Date().getTime()));
//                    sideBoardCellDetail.setCell(boardCells.getCell().toString());
//                    sideBoardCellDetail.setOrderStatus(1);
//                    logger.info("存餐新建sideBoardCellDetail:"+sideBoardCellDetail);
//                    aiyouweiService.insertDetail(sideBoardCellDetail);
//                }
//                Result result = new Result();
//                result.setCode(200);
//                result.setMessage("存餐成功");
//                result.setData(boardCells.getMealCode());
//                return result;
//            }else{
//                return ResultGenerator.genFailResult("无法存餐，当前餐柜无空余柜格。");
//            }
//        }
//    }
//
//
//    /**
//     *订单页面查询订单状态
//     * @param orderId
//     * @return  0未存，1已存未取，2已取
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getOrderStatus/{orderId}")
//    public Map<String,Object> getOrderStatus(@PathVariable String orderId){
//        //根据订单号查询订单状态
//        SideBoardCellDetailExample exam = new SideBoardCellDetailExample();
//        SideBoardCellDetailExample.Criteria example = exam.createCriteria();
//        example.andOrderIdEqualTo(orderId);
//        List<SideBoardCellDetail> slist = aiyouweiService.selectSideBoardCellDetail(exam);
//        Map<String,Object> map = new HashMap<>();
//        if(slist.size()<1){
//            map.put("code","0");
//            return map;
//        }
//        boolean flag = false;
//        //循环订单表
//        for(SideBoardCellDetail s : slist){
//            if(s.getOrderStatus()==2){
//                flag = true;
//            }else{
//                if (s.getOrderStatus()==0){
//                    map.put("code","0");
//                }else{
//                    map.put("code","1");
//                }
//                flag = false;
//            }
//        }
//        String mealCode = aiyouweiService.getSideBoardCellDetailByOrderId(orderId);
//        map.put("mealCode",mealCode);
//        if(flag==false){
//
//            return map;
//        }else{
//            map.put("code","2");
//            return map;
//        }
//    }
//
//    /**
//     * 根据取餐柜id 查询柜格状态
//     * @param id  取餐柜id5
//     * @return
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getAllSideBoardCells/{id}")
//    public Result getAllSideBoardCells(@PathVariable Integer id){
//        List<SideBoardCells> list = aiyouweiService.selectAllSideBoardCell(id);
//        if(list.size()>0){
//            return ResultGenerator.genSuccessResult(list);
//        }else{
//            return ResultGenerator.genFailResult("当前分店不存在该取餐柜！");
//        }
//    }
//
//    /**
//     * 查询分店对应的取餐柜
//     * @param shopId
//     * @return
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getSideBoardByShopIdAndBranchId/{shopId}/{branchId}")
//    public Result getSideBoardsByShopId(@PathVariable Integer shopId,@PathVariable Integer branchId){
//        SideBoardExample sideBoardExample = new SideBoardExample();
//        SideBoardExample.Criteria criteria =  sideBoardExample.createCriteria();
//        criteria.andShopIdEqualTo(shopId);
//        criteria.andBranchIdEqualTo(branchId);
//        criteria.andStatusEqualTo(true);
//        List<SideBoard> sideBoards = sideBoardMapper.selectByExample(sideBoardExample);
//        if(sideBoards.size()>0){
//            return ResultGenerator.genSuccessResult(sideBoards);
//        }else{
//            return ResultGenerator.genFailResult("未查询到取餐柜!");
//        }
//    }
//
//    /**
//     * 查询商户是否有取餐柜
//     * @param shopId
//     * @return
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getSideBoardByShopId/{shopId}")
//    public Result getSideBoardsByShopId_(@PathVariable Integer shopId){
//        SideBoardExample sideBoardExample = new SideBoardExample();
//        SideBoardExample.Criteria criteria =  sideBoardExample.createCriteria();
//        criteria.andShopIdEqualTo(shopId);
//        criteria.andStatusEqualTo(true);
//        List<SideBoard> sideBoards = sideBoardMapper.selectByExample(sideBoardExample);
//        if(sideBoards.size()>0){
//            return ResultGenerator.genSuccessResult(sideBoards);
//
//        }else{
//            return ResultGenerator.genFailResult("未查询到取餐柜!");
//        }
//    }
//
//
//    /**
//     * 取餐码开柜
//     * @param saveOrderForm
//     * @return
//     * @throws IOException
//     */
//    @PostMapping(value = "/api/wxapp/aiyouwei/openCellsByMealCode")
//    public Result openCellsByCode(SaveOrderForm saveOrderForm)throws IOException{
//        //查找到所有的当前取餐码对应的格子并添加到cellNo中
//        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
//        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
//        criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
//        List<SideBoardCellDetail> list = sideBoardCellDetailMapper.selectByExample(example);
//        String [] cellNo = new String[list.size()];
//        for(int i = 0;i < list.size();i++){
//            cellNo[i] = list.get(i).getCell();
//        }
//        SideBoard sideBoard = aiyouweiService.getSideBoardByMealCode(saveOrderForm.getMealCode());
//        String res = aiyouweiUtils.runCommand(cellNo, CommandCode.OPEN.getCode(),sideBoard);
//        Map<String,Object> obj = getRes(res);
//        if(((Boolean)obj.get("Success")).booleanValue() == false){
//            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
//        }
//        return ResultGenerator.genSuccessResult("开柜成功！");
//    }
//
//    /**
//     * 批量开柜
//     * @param id
//     * @param cells
//     * @return
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/openCellByCellNo")
//    public Result openCellsByCellNo(Integer id,String  cells)throws IOException{
//        SideBoard sideBoard = aiyouweiService.selectById(id);
//        UmengPushVo pushVo = new UmengPushVo();
//        pushVo.setCellNo(cells.split(","));
//        //设置提示信息,内容是文章标题
//        //用户开柜取餐如果该订单是保温订单则执行关闭保温操作
//        String str = JSON.toJSONString(pushVo);
//        logger.info("调用开柜接口:"+pushVo);
//        Map<String, String> parm = new HashMap<String, String>();
//        parm.put("msg",str);
//        parm.put("id",sideBoard.getJpushRegisterId());
//        Boolean flag = JPushUtil.jpushAndroid(parm);
//        if(flag == true){
//            return ResultGenerator.genSuccessResult("开柜成功");
//        }else{
//            return ResultGenerator.genFailResult("开柜失败");
//        }
//
//    }
//
//    /**
//     * 效验取餐码是否正确
//     * @param saveOrderForm
//     * @return
//     */
//    @PostMapping(value = "/api/wxapp/aiyouwei/isTrueCode")
//    public Result isTrueCode(@RequestBody SaveOrderForm saveOrderForm){
//
//        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
//        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
//        criteria.andOrderStatusEqualTo(0);
//        criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
//        List<SideBoardCellDetail> sideBoardCellDetails = sideBoardCellDetailMapper.selectByExample(example);
//        if(sideBoardCellDetails.size()>0){
//            return ResultGenerator.genSuccessResult(true);
//        }else{
//            return ResultGenerator.genFailResult("取餐订单不存在!");
//        }
//    }
//
//    /**
//     * 存餐码开柜存餐
//     * @param saveOrderForm
//     * @return
//     * @throws ParseException
//     * @throws IOException
//     */
//    @PostMapping(value = "/api/wxapp/aiyouwei/saveOrderByMealCode")
//    public Result saveOrdersByMealCode(@RequestBody SaveOrderForm saveOrderForm)throws IOException{
//        //开柜流程
//        //
//        //效验柜子号
//        SideBoardCellDetailExample example = new SideBoardCellDetailExample();
//        SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
//        criteria.andOrderStatusEqualTo(0);
//        criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
//
//        List<SideBoardCellDetail> sbDetails = sideBoardCellDetailMapper.selectByExample(example);
//
//        if(sbDetails.size()<=0 || null == sbDetails){
//            //取餐码不存在
//            return ResultGenerator.genFailResult("取餐码错误!");
//        }
//        String [] cells = saveOrderForm.getCellNo().split(",");
//        //取餐码存在时
//        //开启用户选择的柜格
//        //暂时未加判断，默认成功
//
////        String s = aiyouweiUtils.runCommand(
////                cells, CommandCode.OPEN.getCode(),aiyouweiService.selectById(Integer.valueOf(saveOrderForm.getSideBoardId())));
////        Map<String,Object> obj = getRes(s);
////        if(((Boolean)obj.get("Success")).booleanValue() == false){
////            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////        }
//        SideBoardCellDetailExample exam = new SideBoardCellDetailExample();
//        SideBoardCellDetailExample.Criteria cri =  exam.createCriteria();
//        cri.andMealCodeEqualTo(saveOrderForm.getMealCode());
//        cri.andShopIdEqualTo(saveOrderForm.getShopId());
//        cri.andBranchIdEqualTo(saveOrderForm.getBranchId());
//        cri.andOrderStatusEqualTo(0);
//        List<SideBoardCellDetail> cellDetails = sideBoardCellDetailMapper.selectByExample(exam);
//        for(String cell : cells){
//            //1.首先查询该分店对应的柜子
//            AiyouweiGetCellVO aiyouweiGetCellVO =
//                    aiyouweiService.selectCell(saveOrderForm.getBranchId(),saveOrderForm.getShopId(),Integer.valueOf(cell));
//            String[] cellNo = new String[]{aiyouweiGetCellVO.getCell().toString()};
//            //开柜还没加判断
//            //开柜成功更新记录
//            //cells表更新记录后做判断
//            String code = aiyouweiService.isOneOrderToSomeCell(cellDetails.get(0).getOrderId());
//            if("".equals(code)){
//                code = aiyouweiService.getMealCode(cellDetails.get(0).getOrderId());
//            }
//            SideBoardCells boardCells =  SideBoardCells.builder().id(aiyouweiGetCellVO.getId()).
//                    status(true).cell(aiyouweiGetCellVO.getCell()).
//                    orderId(cellDetails.get(0).getOrderId()).mealCode(code).
//                    sideBoardId(aiyouweiGetCellVO.getSideBoardId()).build();
//            aiyouweiService.updateSideBoardCells(boardCells);
//            List<SideBoardCellDetail> sideBoardCellDetails = aiyouweiService.getSideBoardCellsExample(cellDetails.get(0).getOrderId());
//            List<SideBoardCells> sideBoardCells = aiyouweiService.getSideBoardCells(cellDetails.get(0).getOrderId());
//            if(sideBoardCells.size() <= sideBoardCellDetails.size()){
//                sideBoardCellDetails.get(0).setStartTime(new Timestamp(new Date().getTime()));
//                sideBoardCellDetails.get(0).setCell(boardCells.getCell().toString());
//                sideBoardCellDetails.get(0).setOrderStatus(1);
//                aiyouweiService.updateSideBoardCellDetail(sideBoardCellDetails.get(0));
//            }else{
//                SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
//                sideBoardCellDetail.setMealCode(code);
//                sideBoardCellDetail.setId(0);
//                sideBoardCellDetail.setShopId(saveOrderForm.getShopId());
//                sideBoardCellDetail.setBranchId(saveOrderForm.getBranchId());
//                sideBoardCellDetail.setOrderId(cellDetails.get(0).getOrderId());
//                sideBoardCellDetail.setStartTime(new Timestamp(new Date().getTime()));
//                sideBoardCellDetail.setCell(boardCells.getCell().toString());
//                sideBoardCellDetail.setOrderStatus(1);
//                aiyouweiService.insertDetail(sideBoardCellDetail);
//            }
//        }
//        Result result = new Result();
//        result.setCode(200);
//        result.setMessage("存餐成功");
//        result.setData(saveOrderForm.getMealCode());
//        return result;
//    }
//
//    /**
//     *刷卡取餐
//     * @param
//     * @return
//     */
//    @PostMapping("/api/wxapp/aiyouwei/openCellByCard")
//    public Result openCellByCard(@RequestBody SaveOrderForm saveOrderForm)throws Exception{
//        logger.info("进入刷卡取餐方法，入参:"+saveOrderForm);
//        PayCard payCard = new PayCard();
//        if(null != saveOrderForm.getCustomerCode()){
//            payCard  =  payCardMapper.selectByPayCode(saveOrderForm.getCustomerCode());
//            logger.info(payCard.toString());
//            Calendar calendar=Calendar.getInstance();
//            calendar.add(Calendar.MINUTE,-1);
//            Date date=calendar.getTime();
//            if (date.after(payCard.getPayCodeTime())){
//                return ResultGenerator.genFailResult("二维码已过期！");
//            }
//            logger.info("查找会员卡结果:"+payCard.toString());
//        }else{
//            logger.info("根据卡号查找会员");
//            //1.根据卡号搜索
//            SideBoardVO sideBoardVO =
//                    sideBoardMapper.selectByShopIdAndBranchId(saveOrderForm.getBranchId(),saveOrderForm.getShopId(),saveOrderForm.getCashierDeskId());
//            Condition condition = new Condition(YpCard.class);
//            condition.or().andEqualTo("cardMenjinId",saveOrderForm.getCardNo());
//            String cardNo = ypCardMapper.selectByCondition(condition).get(0).getCardNo();
//            payCard  = payCardMapper.selectPayCardByCardNo(cardNo);
//            logger.info("查找会员卡结果:"+payCard.toString());
//        }
//
//        if(null == payCard ){
//            return ResultGenerator.genFailResult("该卡号未绑定会员！");
//        }
//        logger.info("查找所有存餐中的订单");
//        //查找所有存餐中的订单
//        List<OpenCellByCardNoVO> openCellByCardNoForm = sideBoardCellDetailMapper.selectByCustomerId(payCard.getCustomerid());
//        if(openCellByCardNoForm.size()<=0){
//            return ResultGenerator.genFailResult("取餐失败,该用户无存餐中的订单！");
//        }
//        logger.info("根据订单id从数据库中查找cashierId,orderId:"+openCellByCardNoForm.get(0).getOrderId());
//        List<Integer> sideBoardId = sideBoardCellsMapper.selectSideboardIdByOrderId(openCellByCardNoForm.get(0).getOrderId());
//        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(sideBoardId.get(0));
//        //如果查询出来了就开柜
//        String [] cellNo = new String[openCellByCardNoForm.size()];
//        String [] warmCell = new String[openCellByCardNoForm.size()];
//
//        for(int i = 0; i < openCellByCardNoForm.size(); i++){
//            cellNo[i] = openCellByCardNoForm.get(i).getCell();
//
//        }
////        SideBoard sideBoard = new SideBoard();
////        sideBoard.setDeviceId(sideBoardVO.getDeviceId());
////        sideBoard.setAppid(sideBoardVO.getAppid());
//        UmengPushVo pushVo = new UmengPushVo();
//        pushVo.setCellNo(cellNo);
//        //取餐时关灯
//        pushVo.setLight(false);
//        pushVo.setOpen(true);
//        //设置提示信息,内容是文章标题
//        //用户开柜取餐如果该订单是保温订单则执行关闭保温操作
//        String str = JSON.toJSONString(pushVo);
//        logger.info("调用开柜接口:"+pushVo);
//        Map<String, String> parm = new HashMap<String, String>();
//        parm.put("msg",str);
//        parm.put("id",sideBoard.getJpushRegisterId());
//        Boolean flag = JPushUtil.jpushAndroid(parm);
//        //Boolean flag = umengPushService.sendAndroidBroadcast(pushVo);
//        if(!flag){
//            return ResultGenerator.genFailResult("开柜失败！");
//        }
////        //调用开柜命令
////        String res = aiyouweiUtils.runCommand(cellNo, CommandCode.OPEN.getCode(),sideBoard);
////        logger.info("执行开柜方法成功:"+res);
////        Map<String,Object> obj = getRes(res);
////        if(((Boolean)obj.get("Success")).booleanValue() == false){
////            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////        }
////        //调用加热命令
////        String warmRes = aiyouweiUtils.runCommand(warmCell, "1026",sideBoard);
////        obj = getRes(warmRes);
////        if(((Boolean)obj.get("Success")).booleanValue() == false){
////            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////        }
//        //更新SideBoardCellDetail和 sideBoardCells
//        for(int i = 0; i < openCellByCardNoForm.size(); i++){
//            SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
//            sideBoardCellDetail.setId(openCellByCardNoForm.get(i).getId());
//            sideBoardCellDetail.setEndTime(new Timestamp(new Date().getTime()));
//            sideBoardCellDetail.setOrderStatus(2);
//            sideBoardCellDetailMapper.updateByPrimaryKeySelective(sideBoardCellDetail);
//            SideBoardCells sideBoardCells =
//                    sideBoardCellsMapper.selectByCellAndMealCodeAndOrderNo(Integer.valueOf(openCellByCardNoForm.get(i).getCell()),
//                            openCellByCardNoForm.get(i).getMealCode(),openCellByCardNoForm.get(i).getOrderId());
//            System.err.println(sideBoardCells);
//            sideBoardCells.setStatus(false);
//            sideBoardCells.setIsWarm(false);
//            sideBoardCells.setMealCode("");
//            sideBoardCells.setOrderId("");
//            sideBoardCellsMapper.updateByPrimaryKeySelective(sideBoardCells);
//        }
//        return ResultGenerator.genSuccessResult("取餐成功");
//
//    }
//
//
//    /**
//     *人脸取餐
//     * @param
//     * @return
//     */
//    @PostMapping("/api/wxapp/aiyouwei/openCellByFace")
//    public Result openCellByFace(@RequestBody SaveOrderForm saveOrderForm)throws Exception{
//        //1.根据卡号搜索
//        SideBoardVO sideBoardVO =
//                sideBoardMapper.selectByShopIdAndBranchId(saveOrderForm.getBranchId(),saveOrderForm.getShopId(),saveOrderForm.getCashierDeskId());
//        String imgName = System.currentTimeMillis()+"";
//        String filePath = "/usr/local/nginx/html/images/faces/"+imgName+".jpg";
//
//        String faceUrl = filePath.replace(wxapiFilepath, "http://" + ipAddress);
////        String faceUrl = "https://binguoai.com/images/faces/"+imgName+".jpg";
////        //测试配置
////        filePath = "C:\\upload\\"+imgName+".jpg";
////        String faceUrl = "http://123.206.224.209:1444/upload/"+imgName+".jpg";
//        boolean isSuceess = Base64ToImage(saveOrderForm.getImg64(),filePath);
//        if(false == isSuceess){
//            return ResultGenerator.genFailResult("base64转图片失败！");
//        }
//        //faceUrl = "http://binguoai.com/wxfaces/6046528b-e13a-4e1d-8220-172d79e1a5eb.png";
//        com.tencentcloudapi.iai.v20180301.models.Result[] results
//                = FaceHelperV3.searchFacesFromSingleShop(faceUrl, saveOrderForm.getShopId().toString());
//
//        Integer customerId = null;
//        if (results != null && results.length > 0) {
//            for (com.tencentcloudapi.iai.v20180301.models.Result result : results) {
//                //验证成功策略：confidence值大于90
//                if (result.getCandidates()[0].getScore() > 90) {
//                    String temp = result.getCandidates()[0].getPersonId();
//                    if (temp.contains("_")) {
//
//                        customerId = Integer.valueOf(temp.split("_")[1]);
//                    } else {
//                        customerId = Integer.valueOf(temp);
//                    }
//                    break;
//                }else{
//                    return ResultGenerator.genFailResult("取餐失败,人脸识别失败！");
//
//                }
//            }
//        }
//        List<OpenCellByCardNoVO> openCellByCardNoForm = sideBoardCellDetailMapper.selectByCustomerId(customerId);
//        if(openCellByCardNoForm.size()<=0){
//            return ResultGenerator.genFailResult("取餐失败,该用户无存餐中的订单！");
//        }
//        logger.info("根据订单id从数据库中查找cashierId,orderId:"+openCellByCardNoForm.get(0).getOrderId());
//        boolean flag = true;
//        List<Integer> sideBoardId = new ArrayList<>();
//        while (flag){
//         sideBoardId = sideBoardCellsMapper.selectSideboardIdByOrderId(openCellByCardNoForm.get(0).getOrderId());
//            if(sideBoardId != null){
//                flag = false;
//            }
//        }
//        SideBoard sideBoard = sideBoardMapper.selectByPrimaryKey(sideBoardId.get(0));
//
//        //如果查询出来了就开柜
//        String [] cellNo = new String[openCellByCardNoForm.size()];
//        String [] warmCell = new String[openCellByCardNoForm.size()];
////        int flag = 0;
////        for(int i = 0; i < openCellByCardNoForm.size(); i++){
////            cellNo[i] = openCellByCardNoForm.get(i).getCell();
////            if(null != openCellByCardNoForm.get(i).getIsWarm()){
////                warmCell[flag] = openCellByCardNoForm.get(i).getCell();
////                flag += 1;
////            }
////
////        }
//        for(int i = 0; i < openCellByCardNoForm.size(); i++){
//            cellNo[i] = openCellByCardNoForm.get(i).getCell();
//        }
////        SideBoard sideBoard = new SideBoard();
////        sideBoard.setDeviceId(sideBoardVO.getDeviceId());
////        sideBoard.setAppid(sideBoardVO.getAppid());
////        //调用开柜命令
////        String res = aiyouweiUtils.runCommand(cellNo, CommandCode.OPEN.getCode(),sideBoard);
////        Map<String,Object> obj = getRes(res);
////        if(((Boolean)obj.get("Success")).booleanValue() == false){
////            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
////        }
////        //调用加热命令
////        String warmRes = aiyouweiUtils.runCommand(warmCell, "1026",sideBoard);
////        obj = getRes(warmRes);
////        if(((Boolean)obj.get("Success")).booleanValue() == false){
////            return ResultGenerator.genFailResult((String.valueOf(obj.get("Msg"))));
//
//        UmengPushVo pushVo = new UmengPushVo();
//        pushVo.setCellNo(cellNo);
//        //取餐时关灯
//        pushVo.setLight(false);
//        pushVo.setOpen(true);
//        //设置提示信息,内容是文章标题
//        //用户开柜取餐如果该订单是保温订单则执行关闭保温操作
//        String str = JSON.toJSONString(pushVo);
//        logger.info("调用开柜接口:"+pushVo);
//        Map<String, String> parm = new HashMap<String, String>();
//        parm.put("msg",str);
//        parm.put("id",sideBoard.getJpushRegisterId());
//        flag = JPushUtil.jpushAndroid(parm);
//        //Boolean flag = umengPushService.sendAndroidBroadcast(pushVo);
//        if(!flag){
//            return ResultGenerator.genFailResult("开柜失败！");
//        }
//        //更新SideBoardCellDetail和 sideBoardCells
//        for(int i = 0; i < openCellByCardNoForm.size(); i++){
//            SideBoardCellDetail sideBoardCellDetail = new SideBoardCellDetail();
//            sideBoardCellDetail.setId(openCellByCardNoForm.get(i).getId());
//            sideBoardCellDetail.setEndTime(new Timestamp(new Date().getTime()));
//            sideBoardCellDetail.setOrderStatus(2);
//            SideBoardCells sideBoardCells =
//                    sideBoardCellsMapper.selectByCellAndMealCodeAndOrderNo(Integer.valueOf(openCellByCardNoForm.get(i).getCell()),
//                            openCellByCardNoForm.get(i).getMealCode(),openCellByCardNoForm.get(i).getOrderId());
//            sideBoardCells.setStatus(false);
//            sideBoardCells.setIsWarm(false);
//            sideBoardCells.setMealCode("");
//            sideBoardCells.setOrderId("");
//            sideBoardCellsMapper.updateByPrimaryKeySelective(sideBoardCells);
//            sideBoardCellDetailMapper.updateByPrimaryKeySelective(sideBoardCellDetail);
//        }
//        return ResultGenerator.genSuccessResult("取餐成功");
//
//    }
//
//    @PostMapping("/api/wxapp/aiyouwei/deletePersion")
//    public Result deletePersion(){
//        String customerId = "23_16373";
//        String shopID = "23";
//        FaceHelperV3.deletePerson(customerId);
//        return null;
//    }
//
//
//    /**
//     * base64字符串转换成图片 (对字节数组字符串进行Base64解码并生成图片)
//     * @param imgStr		base64字符串
//     * @param imgFilePath	指定图片存放路径  （注意：带文件名）
//     * @return
//     */
//    public boolean Base64ToImage(String imgStr,String imgFilePath) {
//        if (StringUtil.isEmpty(imgStr)) // 图像数据为空
//            return false;
//
//        BASE64Decoder decoder = new BASE64Decoder();
//        try {
//            // Base64解码
//            byte[] b = decoder.decodeBuffer(imgStr);
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {// 调整异常数据
//                    b[i] += 256;
//                }
//            }
//
//            OutputStream out = new FileOutputStream(imgFilePath);
//            out.write(b);
//            out.flush();
//            out.close();
//
//            return true;
//        } catch (Exception e) {
//            System.out.println(e.getMessage());
//            return false;
//        }
//    }
//
//
//    public Map<String,Object> getRes(String res){
//        Map<String,Object> map = new HashMap<>();
//        map = JSON.parseObject(res, HashMap.class);
//        return map;
//
//    }
//
//    /**
//     * 手机号存餐
//     * @param form
//     * @return
//     */
//    @PostMapping("/api/wxapp/aiyouwei/saveOrderByPhone")
//    public Result saveOrderByPhone(@RequestBody PhoneMealsForm form)throws Exception{
//        logger.info("进入手机号存餐订单,入参:"+form.toString());
//        SideBoardVO sideBoardVO = new SideBoardVO();
//        Shop shop = shopMapper.selectByPrimaryKey(Shop.builder().id(form.getShopId()).build());
//        if(null == shop.getShopType() ){
//            sideBoardVO = aiyouweiService.phoneMeals(form);
//        }else if(2 ==  shop.getShopType()){
//            Customer customer = apiService.isShopCustomer(form.getPhone(),shop);
//            if(null == customer){
//                return ResultGenerator.genFailResult("非商户绑定用户无法存餐");
//            }
//            logger.info("进入手机号存餐订单,入参:"+form.toString());
//            form.setShopId(shop.getId());
//            sideBoardVO = aiyouweiService.phoneMealApi(form,customer);
//
//        }
//        if(null != sideBoardVO){
//            SaveOrderForm saveOrderForm = new SaveOrderForm();
//            saveOrderForm.setShopId(sideBoardVO.getShopId());
//            saveOrderForm.setBranchId(sideBoardVO.getBranchId());
//            saveOrderForm.setMealCode(sideBoardVO.getMealCode());
//            saveOrderForm.setCashierDeskId(sideBoardVO.getSideBranchId());
//            saveOrderForm.setPhone(form.getPhone());
//            logger.info("发送短信取餐码短信，参数:phone"+saveOrderForm.getPhone()+"取餐码:"+saveOrderForm.getMealCode());
//            JavaSmsApi.sendQuCanGuiCodeVerify(saveOrderForm.getPhone(),saveOrderForm.getMealCode(),sideBoardVO.getSideBranchId().toString());
//            return this.openByWxButton(saveOrderForm);
//        }else{
//            return ResultGenerator.genFailResult("存餐失败!");
//        }
//    }
//
//    /**
//     * 检查订单支付状态
//     * @param saveOrderForm
//     * @return
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/beforeOpenCell")
//    public Result beforeOpenCell(SaveOrderForm saveOrderForm)throws Exception{
//        if(null != saveOrderForm.getMealCode() ){
//            //效验柜子号
//            SideBoardCellDetailExample example = new SideBoardCellDetailExample();
//            SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
//            criteria.andOrderStatusBetween(0,1);
//            criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
//            criteria.andShopIdEqualTo(saveOrderForm.getShopId());
//            criteria.andBranchIdEqualTo(saveOrderForm.getBranchId());
//            List<SideBoardCellDetail> sbDetails = sideBoardCellDetailMapper.selectByExample(example);
//            if(sbDetails.size()<=0 || null == sbDetails ){
//                //取餐码不存在
//                return ResultGenerator.genFailResult("号码无效!");
//            }
//            saveOrderForm.setOrderId(sbDetails.get(0).getOrderId());
//        }
//        //查询商户id 和 分店id
//        BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
//        //如果订单是未支付的状态那么则返回401状态码和存取餐数据，让用户选择支付方式
//        if(0==binguoOrder.getPaystatus() && binguoOrder.getRealfee()!=0){
//            Result result = new Result();
//            result.setCode(401);
//            result.setMessage("FAIL");
//            result.setData(saveOrderForm);
//            System.out.println("判断订单状态接口:"+saveOrderForm);
//            return result;
//        }else{
//            return this.openByWxButton(saveOrderForm);
//        }
//    }
//
//    /**
//     * 获取支付二维码
//     * @param saveOrderForm
//     * @return
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getPayCode")
//    public Result getPayCode(SaveOrderForm saveOrderForm){
//        if(null != saveOrderForm.getMealCode() ){
//            //效验柜子号
//            SideBoardCellDetailExample example = new SideBoardCellDetailExample();
//            SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
//            criteria.andOrderStatusBetween(0,1);
//            criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
//            criteria.andShopIdEqualTo(saveOrderForm.getShopId());
//            criteria.andBranchIdEqualTo(saveOrderForm.getBranchId());
//            List<SideBoardCellDetail> sbDetails = sideBoardCellDetailMapper.selectByExample(example);
//            if(sbDetails.size()<=0 || null == sbDetails ){
//                //取餐码不存在
//                return ResultGenerator.genFailResult("号码无效!");
//            }
//            saveOrderForm.setOrderId(sbDetails.get(0).getOrderId());
//        }
//        String code = "";
//        try{
//            BinguoOrder binguoOrder = binguoOrderMapper.findOrderByOrderNo(saveOrderForm.getOrderId());
//            System.out.println(binguoOrder.toString());
//            code = qrCodePayQCGService.createQrCodePayQCG(saveOrderForm.getOrderId(),binguoOrder.getRealfee(),saveOrderForm.getShopId(),saveOrderForm.getPayType());
//            System.out.println("CODE:"+code);
//            saveOrderForm.setImg64(code);
//        }catch (Exception e){
//            return ResultGenerator.genFailResult(e.getMessage());
//        }
//        //返回code的base64编码
//        return ResultGenerator.genSuccessResult(saveOrderForm);
//    }
//
//    /**
//     * 查询支付状态
//     * @param saveOrderForm
//     * @return
//     * @throws IOException
//     */
//    @GetMapping(value = "/api/wxapp/aiyouwei/getPayResult")
//    public Result getPayResult(SaveOrderForm saveOrderForm){
//        logger.info("进入查询支付状态接口，入参:"+saveOrderForm);
//        if(null != saveOrderForm.getMealCode() ){
//            //效验柜子号
//            SideBoardCellDetailExample example = new SideBoardCellDetailExample();
//            SideBoardCellDetailExample.Criteria criteria = example.createCriteria();
//            criteria.andOrderStatusBetween(0,1);
//            criteria.andMealCodeEqualTo(saveOrderForm.getMealCode());
//            criteria.andShopIdEqualTo(saveOrderForm.getShopId());
//            criteria.andBranchIdEqualTo(saveOrderForm.getBranchId());
//            List<SideBoardCellDetail> sbDetails = sideBoardCellDetailMapper.selectByExample(example);
//            if(sbDetails.size()<=0 || null == sbDetails ){
//                //取餐码不存在
//                return ResultGenerator.genFailResult("号码无效!");
//            }
//            if (null == saveOrderForm.getCashierDeskId()){
//                saveOrderForm.setCashierDeskId(1726);
//            }
//            saveOrderForm.setOrderId(sbDetails.get(0).getOrderId());
//        }
//        Result result = new Result();
//        String orderNo = saveOrderForm.getOrderId();
//        try{
//            logger.info("调用二维码订单支付状态查询接口，入参:"+ orderNo);
////            if(orderNo.startsWith("Z")){
////                orderNo = orderNo.substring(1);
////            }else if(orderNo.startsWith("S")){
////                orderNo = orderNo.substring(2);
////            }
//            JSONObject jsonObject = qrCodePayQCGService.queryPayResult(orderNo);
//            String code = jsonObject.get("code").toString();
//            logger.info("二维码订单支付状态查询完毕,返回值:"+jsonObject.toString());
//            if(code.equals("1")){
//                saveOrderForm.setCustomerId(0000);
//                saveOrderForm.setIsCustomer("true");
//                saveOrderForm.setOrderId(saveOrderForm.getOrderId());
//                return this.openByWxButton(saveOrderForm);
//            }else{
//                result.setCode(400);
//                result.setMessage("FAIL");
//                saveOrderForm.setOrderId(orderNo);
//                result.setData(saveOrderForm);
//                return result;
//            }
//        }catch (Exception e){
//            return ResultGenerator.genFailResult(e.getMessage());
//        }
//    }
//
//    @GetMapping(value = "/api/wxapp/aiyouwei/getBaiduSDKSerial")
//    public Result getBaiduSDKSerial(String deviceId){
//        logger.info("进入getBaiduSDKSerial方法,入参:"+deviceId);
//        String serial = aiyouweiService.getBaiduSDKSerial(deviceId);
//        if(null == serial){
//            logger.info("----------该设备未初始化，正在分配序列号,请稍后");
//            BaiduSdkSerialNum baiduSdkSerialNum = aiyouweiService.getNoUseBaiduSDKSerial();
//            if(null == baiduSdkSerialNum){
//                return ResultGenerator.genFailResult("初始化失败,序列号已用光！");
//            }else{
//                logger.info("----------查找最新一条未使用的序列号:"+baiduSdkSerialNum);
//                baiduSdkSerialNum.setDeviceId(deviceId);
//                baiduSdkSerialNum.setStatus(true);
//                int i = aiyouweiService.serialBindSideBoard(baiduSdkSerialNum);
//                if(i>0){
//                    logger.info("序列号分配成功,号码为:"+baiduSdkSerialNum.getSerialNumber());
//                    return ResultGenerator.genSuccessResult(baiduSdkSerialNum.getSerialNumber());
//                }else{
//                    return ResultGenerator.genFailResult("序列号分配失败,失败原因:数据库更新失败！");
//                }
//            }
//        }else{
//            logger.info("查询成功,返回结果:"+serial);
//            return ResultGenerator.genSuccessResult(serial);
//        }
//    }
//
//    @GetMapping(value = "/api/wxapp/aiyouwei/getSideBoardInitStatus")
//    public Result getSideBoardInitStatus(String deviceId){
//        logger.info("进入获取设备绑定状态方法,入参:"+deviceId);
//        InitInfo initInfo = initInfoMapper.selectByDeviceId(deviceId);
//        if(null != initInfo){
//            return ResultGenerator.genFailResult("设备还未初始化");
//        }
//        logger.info("根据设备id找到取餐柜id:"+initInfo.getCashierdeskid());
//        SideBoard sideBoard = sideBoardMapper.selectByCashierId(initInfo.getCashierdeskid());
//        if(null == sideBoard.getJpushRegisterId()){
//            return ResultGenerator.genFailResult("");
//        }else{
//            return ResultGenerator.genSuccessResult(true);
//        }
//    }
//
//    @PostMapping(value = "/api/wxapp/aiyouwei/updateJpushRegisterId")
//    public Result updateJpushRegisterId(@RequestBody SideBoardVO sideBoardVO){
//        logger.info("进入获取设备更新柜格状态方法,入参:"+sideBoardVO);
//
//        if(sideBoardVO.getCashierDeskId() == null
//                || sideBoardVO.getJpushRegisterId() == null
//                || sideBoardVO.getCellNum() == 0){
//            return ResultGenerator.genFailResult("参数错误！");
//        }
//        //InitInfo initInfo = initInfoMapper.selectByDeviceId(sideBoardVO.getDeviceId());
//        /*if(null == initInfo){
//            return ResultGenerator.genFailResult("设备还未初始化");
//        }*/
//        logger.info("根据设备id找到取餐柜id:"+sideBoardVO.getCashierDeskId());
//        SideBoard sideBoard = sideBoardMapper.selectByCashierId(sideBoardVO.getCashierDeskId());
//        sideBoard.setJpushRegisterId(sideBoardVO.getJpushRegisterId());
//        sideBoard.setParentId(0);
//        //查找出
//        Integer sideBranchId = sideBoardMapper.selectMaxSideBranchId(sideBoard.getBranchId(),sideBoard.getShopId());
//        sideBoard.setBranchSideBoardId(sideBranchId+1);
//        sideBoardMapper.updateByPrimaryKeySelective(sideBoard);
//        logger.info("更新sideBoard表成功,更新字段JpushRegisterId，更新值:"+sideBoardVO.getJpushRegisterId());
//        for(int i = 0; i < sideBoardVO.getCellNum(); i++){
//            try {
//                sideBoardCellsMapper.insertSelective(SideBoardCells.builder().id(0).sideBoardId(sideBoard.getId()).isWarm(null)
//                        .status(false).cell(i+1).mealCode(null).orderId(null).build());
//            }catch (Exception e){
//                return ResultGenerator.genFailResult(e.getMessage());
//            }
//        }
//        logger.info("初始化sideBoardCell表成功");
//        return ResultGenerator.genSuccessResult(true);
//
//    }
//    /**
//     * 手机号存餐
//     * @param form
//     * @return
//     */
//    @PostMapping("/api/wxapp/aiyouwei/saveOrderByPhoneApi")
//    public Result saveOrderByPhoneApi(@RequestBody PhoneMealsForm form)throws Exception{
//        if (StringUtils.isEmpty(form.getAppId())
//                || StringUtils.isEmpty(form.getSign())
//                || StringUtils.isEmpty(form.getDeviceId())
//                || StringUtils.isEmpty(form.getPhone())
//        ) {
//            throw new ServiceException("参数错误");
//        }
//        TreeMap<String, String> param = new TreeMap<>();
//        param.put("phone",form.getPhone());
//        if(null != form.getBranchId()){
//            param.put("branchId",form.getBranchId().toString());
//        }else{
//            Integer flag = aiyouweiService.selectShopBranchList(form.getAppId());
//            if(-100 == flag){
//                return ResultGenerator.genFailResult("商户下分店超过一家，请输入详细分店id。");
//            }else if(-200 ==  flag){
//                return ResultGenerator.genFailResult("商户异常。");
//            }else if(-300 == flag){
//                return ResultGenerator.genFailResult("商户下无分店！");
//            }else{
//                form.setBranchId(flag);
//            }
//        }
//        if(null != form.getIsWarm()){
//            param.put("isWarm",form.getIsWarm().toString());
//        }else{
//            form.setIsWarm(false);
//        }
//        param.put("deviceId",form.getDeviceId().toString());
//        param.put("appId",form.getAppId());
//        String key = apiService.getKeyByAppID(form.getAppId());
//        String sign = ApiController.generateSign(param,key);
//        logger.info("效验签名！  传入签名:"+form.getSign()+"生成签名:"+sign);
//        if(!form.getSign().equals(sign)){
//            return ResultGenerator.genFailResult("签名失败!");
//        }
//        Shop shop = apiService.isTrueShop(form.getAppId());
//        if(null == shop){
//            return ResultGenerator.genFailResult("商户状态异常!");
//        }
//        Customer customer = apiService.isShopCustomer(form.getPhone(),shop);
//        if(null == customer){
//            return ResultGenerator.genFailResult("非商户绑定用户无法存餐");
//        }
//        logger.info("进入手机号存餐订单,入参:"+form.toString());
//        form.setShopId(shop.getId());
//        SideBoardVO sideBoardVO = aiyouweiService.phoneMealApi(form,customer);
//        if(null != sideBoardVO){
//            SaveOrderForm saveOrderForm = new SaveOrderForm();
//            saveOrderForm.setShopId(sideBoardVO.getShopId());
//            saveOrderForm.setBranchId(sideBoardVO.getBranchId());
//            saveOrderForm.setMealCode(sideBoardVO.getMealCode());
//            saveOrderForm.setCashierDeskId(sideBoardVO.getSideBranchId());
//            saveOrderForm.setPhone(form.getPhone());
//            logger.info("发送短信取餐码短信，参数:phone"+saveOrderForm.getPhone()+"取餐码:"+saveOrderForm.getMealCode());
//            JavaSmsApi.sendQuCanGuiCodeVerify(saveOrderForm.getPhone(),saveOrderForm.getMealCode(),sideBoardVO.getSideBranchId().toString());
//            return this.openByWxButton(saveOrderForm);
//        }else{
//            return ResultGenerator.genFailResult("存餐失败!");
//        }
//    }
//
//    @PostMapping(value = "/api/wxapp/aiyouwei/addSunSideBoard")
//    public Result addSunSideBoard(@RequestBody SideBoardVO sideBoardVO){
//        logger.info("进入增加副柜功能,入参:"+sideBoardVO);
//        if(sideBoardVO.getCashierDeskId() == null
//                || sideBoardVO.getBranchId() == null
//                || sideBoardVO.getShopId() == null
//                || sideBoardVO.getCellNum() == 0){
//            return ResultGenerator.genFailResult("参数错误！");
//        }
//        logger.info("根据设备id找到主柜id:"+sideBoardVO.getCashierDeskId());
//        SideBoard sideBoard = sideBoardMapper.selectByCashierId(sideBoardVO.getCashierDeskId());
//        logger.info("设置副柜参数到sideBoard对象");
//        sideBoard = SideBoard.builder().id(0).branchId(sideBoardVO.getBranchId()).shopId(sideBoardVO.getShopId()).
//                parentId(sideBoard.getId()).status(true).cashierDeskId(sideBoardVO.getCashierDeskId()).
//                branchSideBoardId(sideBoard.getBranchSideBoardId()).jpushRegisterId(sideBoard.getJpushRegisterId()).build();
//        sideBoardMapper.insertSelective(sideBoard);
//        logger.info("新增sideBoard表成功,新增值:"+sideBoard.toString());
//        Integer count = sideBoardMapper.selectCellsCount(sideBoardVO.getCashierDeskId());
//        for(int i = 0; i < sideBoardVO.getCellNum(); i++){
//            try {
//                sideBoardCellsMapper.insertSelective(SideBoardCells.builder().id(0).sideBoardId(sideBoard.getId()).isWarm(null)
//                        .status(false).cell(count+1+i).mealCode(null).orderId(null).build());
//            }catch (Exception e){
//                return ResultGenerator.genFailResult(e.getMessage());
//            }
//        }
//        logger.info("初始化sideBoardCell表成功");
//        return ResultGenerator.genSuccessResult(true);
//    }
//
//    @GetMapping(value = "/api/wxapp/aiyouwei/getSunSideBoard")
//    public Result getSunSideBoard(SideBoardVO sideBoardVO){
//        logger.info("进入增加副柜功能,入参:"+sideBoardVO);
//        if(sideBoardVO.getCashierDeskId() == null
//                ){
//            return ResultGenerator.genFailResult("参数错误！");
//        }
//        logger.info("根据设备id找到主柜id:"+sideBoardVO.getCashierDeskId());
//        List<SideBoard> sideBoards = sideBoardMapper.selectListByCashierId(sideBoardVO.getCashierDeskId());
//        if(null != sideBoards && sideBoards.size()>0){
//            return ResultGenerator.genSuccessResult(sideBoards);
//        }else{
//            return ResultGenerator.genFailResult("查询失败");
//        }
//    }
//
//    @GetMapping(value = "/api/wxapp/aiyouwei/deleteSunBoard")
//    public Result deleteSunBoard(SideBoardVO sideBoardVO){
//        logger.info("进入增加副柜功能,入参:"+sideBoardVO);
//        if(sideBoardVO.getId() == null
//        ){
//            return ResultGenerator.genFailResult("参数错误！");
//        }
//        logger.info("根据设备id找到主柜id:"+sideBoardVO.getCashierDeskId());
//        Integer flag = sideBoardMapper.deleteByPrimaryKey(sideBoardVO.getId());
//        Integer result = sideBoardMapper.updateBySideBoardId(sideBoardVO.getId());
//        if(flag > 0 && result > 0){
//            return ResultGenerator.genSuccessResult("删除成功");
//        }else{
//            return ResultGenerator.genFailResult("删除失败");
//        }
//
//    }
//
//
//
//
//}
